<template>
    <div>
        <el-button plain @click="addAdminVisible = true" v-if="loginUserRole===0">添加管理员</el-button>
        <!--布局容器-->
        <el-container style="height: 500px; border: 1px solid #eee">
            <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
                <el-menu>
                    <el-submenu index="1">
                        <template slot="title">审核</template>
                        <el-menu-item index="1-1">
                            <e-link @click="selectByPage(0)">待审核</e-link>
                        </el-menu-item>
                        <el-menu-item index="1-2">
                            <e-link @click="selectByPage(1)">已审核</e-link>
                        </el-menu-item>
                    </el-submenu>

                    <el-menu-item index="1-2">
                        <e-link @click="getUsers">管理用户</e-link>
                    </el-menu-item>
                </el-menu>
            </el-aside>
            <!--待审核列表-->
            <el-container v-if="index===1&&isAudited===0">
                <el-header >
                        <p>待审核：</p>
                </el-header>
                <el-main>
                    <el-table :data="auditingData">
                        <el-table-column prop="title" label="题目" width="140">
                            <template slot-scope="scope">
                                <el-link @click="readArticle(scope.row)">{{scope.row.title}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="content" label="内容">
                            <template slot-scope="scope">
                                <p>{{scope.row.content.substring(0, Math.min(scope.row.content.length, 40)) + "..."}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="类型">
                        </el-table-column>
                        <el-table-column prop="author" label="作者">
                            <template slot-scope="scope">
                                <el-link @click="getInfo(scope.row)">{{scope.row.author}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="申请时间">
                        </el-table-column>
                        <el-table-column prop="operate" label="操作">
                            <template slot-scope="scope">
                                <el-link @click="handleAuditLinkClick(scope.row)">审核</el-link>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!--分页工具条-->
                    <div class="block">
                        <el-pagination
                        @size-change="handleAuditingSizeChange"
                        @current-change="handleAuditingCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 20, 50]"
                        :page-size="5"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalCount">
                        </el-pagination>
                    </div>
                </el-main>
            </el-container>
                    
            <!--已审核列表-->
            <el-container v-if="index===1&&isAudited===1">
                <el-header>
                    <p>已审核：</p>
                </el-header>
                <el-main>
                    <el-table :data="auditedData">
                        <el-table-column prop="title" label="题目" width="140">
                            <template slot-scope="scope">
                                <el-link @click="readArticle(scope.row)">{{scope.row.title}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="content" label="内容">
                            <template slot-scope="scope">
                                <p>{{scope.row.content.substring(0, Math.min(scope.row.content.length, 40)) + "..."}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="类型">
                        </el-table-column>
                        <el-table-column prop="author" label="作者">
                            <template slot-scope="scope">
                                <el-link @click="getInfo(scope.row)">{{scope.row.author}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="申请时间">
                        </el-table-column>
                        <el-table-column prop="auditor" label="审核人">
                        </el-table-column>
                        <el-table-column prop="result" label="处理结果">
                            <template slot-scope="scope">
                                <p v-if="scope.row.result===1">通过</p>
                                <p v-if="scope.row.result===0">不通过</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="opinion" label="审核意见">
                        </el-table-column>
                        <el-table-column prop="auditTime" label="审核时间" >
                        </el-table-column>
                    </el-table>

                    <!--分页工具条-->
                    <div class="block">
                        <el-pagination
                        @size-change="handleAuditedSizeChange"
                        @current-change="handleAuditedCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 20, 50]"
                        :page-size="5"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalCount">
                        </el-pagination>
                    </div>
                </el-main>
            </el-container>
            <!--用户列表-->
            <el-container v-if="index===2">
                <el-main>
                    <el-table :data="userData">
                        <el-table-column prop="username" label="用户名">
                        </el-table-column>
                        <el-table-column prop="name" label="昵称">
                        </el-table-column>
                        <el-table-column prop="gender" label="性别">
                        </el-table-column>
                        <el-table-column prop="job" label="工作">
                        </el-table-column>
                        <el-table-column prop="address" label="地址">
                        </el-table-column>
                        <el-table-column prop="followCount" label="关注数">
                        </el-table-column>
                        <el-table-column prop="beFollowedCount" label="被关注数">
                        </el-table-column>
                        <el-table-column prop="status" label="状态">
                            <template slot-scope="scope">
                                <p v-if="scope.row.status===1">正常</p>
                                <p v-if="scope.row.status===0">封禁</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="operate" label="操作">
                            <template slot-scope="scope">
                                <el-link @click="lockUser(scope.row)" v-if="scope.row.status===1">封禁</el-link>
                                <el-link @click="unlockUser(scope.row)" v-if="scope.row.status===0">解封</el-link>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!--分页工具条-->
                    <div class="block">
                        <el-pagination
                        @size-change="handleUserSizeChange"
                        @current-change="handleUserCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 20, 50]"
                        :page-size="5"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalCount">
                        </el-pagination>
                    </div>
                </el-main>
            </el-container>
        </el-container>
        

        <!--审核表单-->
        <el-dialog
                title="审核"
                :visible.sync="auditVisible"
                width="30%"
        >
            <el-form label-width="100px" :model="audit" ref="audit">
                <el-form-item label="审核结果" prop="result">
                    <el-radio-group v-model="audit.result">
                        <el-radio label="1">通过</el-radio>
                        <el-radio label="0">不通过</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="审核意见" prop="opinion">
                    <el-input v-model="audit.opinion" type="textarea"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAudit">审核</el-button>
                    <el-button @click="resetForm('audit')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--查看文章表单-->
        <el-dialog
                title="文章详情"
                :visible.sync="readArticleVisible"
                width="30%"
        >
            <h1>{{readingArticle.title}}</h1>
            <hr>
            <p>{{readingArticle.content}}</p>
        </el-dialog>

        <!-- 添加管理员表单-->
        <el-dialog
                title="添加管理员"
                :visible.sync="addAdminVisible"
                width="30%"
        >
            <el-form :model="admin" status-icon :rules="rules" ref="admin" label-width="100px" class="demo-admin">
                <el-form-item label="账号" prop="username">
                    <el-input type="text" v-model="admin.username" placeholder="请输入5-15位账号" ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="admin.password" autocomplete="off" placeholder="请输入5-15位密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input type="password" v-model="admin.checkPassword" autocomplete="off" placeholder="请确认密码"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="name">
                    <el-input type="text" v-model="admin.name" placeholder="请输入您的昵称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addAdmin('admin')">添加</el-button>
                    <el-button @click="resetForm('admin')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    mounted(){
        this.currentPage=1;
        this.selectByPage(0);
        this.getLoginUser();
    },
    methods:{
        //处理待审核数据每页显示条数改变
        handleAuditingSizeChange(val) {
            // 重新设置每页显示的条数
            this.pageSize = val;
            this.selectByPage(0);
        },
        //处理待审核数据当前页码改变
        handleAuditingCurrentChange(val) {
            // 重新设置当前页码
            this.currentPage = val;
            this.selectByPage(0);
        },
        //处理已审核数据每页显示条数改变
        handleAuditedSizeChange(val) {
            // 重新设置每页显示的条数
            this.pageSize = val;
            this.selectByPage(1);
        },
        //处理已审核数据当前页码改变
        handleAuditedCurrentChange(val) {
            // 重新设置当前页码
            this.currentPage = val;
            this.selectByPage(1);
        },
        //处理用户数据每页显示条数改变
        handleUserSizeChange(val) {
            // 重新设置每页显示的条数
            this.pageSize = val;
            this.selectByPage(1);
        },
        //处理用户数据当前页码改变
        handleUserCurrentChange(val) {
            // 重新设置当前页码
            this.currentPage = val;
            this.selectByPage(1);
        },
        // 分页查询审核表
        selectByPage(isAudited){
            this.index=1;
            axios({
                method:'get',
                url:"http://localhost:8080/admin?currentPage="+this.currentPage+"&pageSize="+this.pageSize+"&isAudited="+isAudited,
                headers:{token:localStorage.getItem('token')}
            }).then(resp=>{
                if(isAudited===0){
                    this.auditingData=resp.data.data.rows;
                }else{
                    this.auditedData=resp.data.data.rows;
                }
                this.totalCount=resp.data.data.totalCount;
                this.isAudited=isAudited;
            })
        },
        // 获取登录中的用户身份
        async getLoginUser(){
            if(localStorage.getItem('token')!==null){
                const isValidJwt = await this.checkJwt();
                if(isValidJwt){
                    const parts = localStorage.getItem('token').split('.');
                    if(parts.length>2){
                        const payload = parts[1];
                        const decoded = atob(payload);
                        this.loginUserRole=JSON.parse(decoded).role;
                    }
                }
            }
        },
        // 检查jwt
        async checkJwt(){
            try {  
                const response = await axios({  
                    method: 'get',  
                    url: 'http://localhost:8080/check/' + localStorage.getItem('token')  
                });  
                return response.data.code;
            } catch (error) {  
                return false; 
        }
        },
        //处理审核链接被点击
        handleAuditLinkClick(row){
            this.audit.id=row.id;
            this.auditVisible=true;
        },
        //审核
        handleAudit(){
            axios({
                method:'put',
                url:'http://localhost:8080/admin',
                data:this.audit,
                headers:{token:localStorage.getItem('token')}
            }).then(resp=>{
                if(resp.data.code){
                    this.$message.success("审核成功！");
                    this.selectByPage(0);
                    this.auditVisible=false;
                    this.resetForm('audit')
                }else{
                    this.$message.error(resp.data.msg);
                    this.auditVisible=false;
                }
            })
        },
        //查看文章
        readArticle(row){
            this.readArticleVisible=true;
            this.readingArticle.title=row.title;
            this.readingArticle.content=row.content;
        },
        //获取用户表
        getUsers(){
            this.index=2;
            axios({
                method:'get',
                url:"http://localhost:8080/user?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
            }).then(resp=>{
                this.userData=resp.data.data.rows;
                this.totalCount=resp.data.data.totalCount;
            })
        },
        //封禁用户
        lockUser(row){
            this.$confirm('确定要封禁该用户吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios({
                    method:'get',
                    url:"http://localhost:8080/admin/"+row.id,
                    headers:{token:localStorage.getItem('token')}
                }).then(resp=>{
                    if(resp.data.code){
                        this.$message.success("封禁成功！")
                        this.getUsers();
                    }else{
                        this.$message.error(resp.data.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消封禁'
                });
            });
        },
        //解封用户
        unlockUser(row){
            this.$confirm('确定要解封该用户吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios({
                    method:'delete',
                    url:"http://localhost:8080/admin/"+row.id,
                    headers:{token:localStorage.getItem('token')}
                }).then(resp=>{
                    if(resp.data.code){
                        this.$message.success("解封成功！")
                        this.getUsers();
                    }else{
                        this.$message.error(resp.data.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消解封'
                });
            });
        },

        // 添加管理员方法
        addAdmin(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    axios({
                        method:"post",
                        url:"http://localhost:8080/admin",
                        data:this.admin,
                        headers:{token:localStorage.getItem('token')}
                    }).then(resp =>{
                        // 判断是否存在
                        if(resp.data.code){
                            this.$message.success("添加成功！");
                            this.addAdminVisible=false;                                
                            this.resetForm('admin');
                        }else{
                            this.$message.error(resp.data.msg);
                            this.resetForm('admin');
                            return false;
                        }
                    })
                } else {
                    this.$message.error('输入不符合要求！请检查后重新输入');
                    this.resetForm('user');
                    return false;
                }
            });
        },
        // 重置方法
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
    data(){
         // 检查用户名输入格式
         var checkUsername = (rule, value, callback) => {
                var reg = /^.{5,15}$/;
                if (value === '') {
                    callback(new Error('请输入账号！'));
                } else if(!(reg.test(value))){
                    callback(new Error('长度不符合要求！'));
                } else{
                    callback();
                }
            };
            // 检查第一次密码输入格式
            var validatePass = (rule, value, callback) => {
                var reg = /^.{5,15}$/;
                if (value === '') {
                    callback(new Error('请输入密码！'));
                }else if(!(reg.test(value))){
                    callback(new Error('长度不符合要求！'));
                } else {
                    if (this.admin.checkPassword !== '') {
                        this.$refs.admin.validateField('checkPassword');
                    }
                    callback();
                }
            };
            // 检查第二次密码是否一致
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码！'));
                } else if (value !== this.admin.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
        return{
            //待审核数据
            auditingData:'',
            //已审核数据
            auditedData:'',
            //用户数据
            userData:'',
            //审核对话框是否展示标识
            auditVisible:false,
            //查看文章对话框是否展示标识
            readArticleVisible:false,
            //添加管理员对话框是否展示标识
            addAdminVisible:false,
            //总记录数
            totalCount:0,
            //当前页码
            currentPage: 1,
            //每页显示的条数
            pageSize:5,
            //侧边选择栏
            index:'',
            //是否审核
            isAudited:'',
            //登录中的用户身份
            loginUserRole:'',
            //审核模型
            audit:{
                id:'',
                result:'',
                opinion:'',
            },
            //正在阅读的文章模型
            readingArticle:{
                title:'',
                content:''
            },
            //添加管理员模型
            admin:{
                username:'',
                password:'',
                checkPassword:'',
                name:''
            },
            rules: {
                username: [
                    { validator: checkUsername, trigger: 'blur' }
                ],
                password: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                checkPassword: [
                    { validator: validatePass2, trigger: 'blur' }
                ]
            }
        }
    }

}
</script>

<style>
    .el-header {
        background-color: #B3C0D1;
        color: #333;
        line-height: 60px;
    }
    
    .el-aside {
        color: #333;
    }
</style>